from typing import Optional
import jwt
from fastapi import Depends, Header, HTTPException, Request
from app.core.ctx import CTX_USER_ID
from app.settings.config import settings
from app.models import User


class AuthControl:

    @classmethod
    async def is_authed(
        cls, token: str = Header(...,
                                 description="认证token")) -> Optional["User"]:
        """
        认证用户
        """
        try:
            if token == "dev":
                user = await User.filter().first()
                user_id = user.id
            else:
                decode_data = jwt.decode(token,
                                         settings.SECRET_KEY,
                                         algorithms=settings.JWT_ALGORITHM)
                user_id = decode_data.get("user_id")
            user = await User.get(id=user_id).first()
            if not user:
                raise HTTPException(status_code=401, detail="用户不存在")
            CTX_USER_ID.set(user_id)
            return user
        except jwt.DecodeError:
            raise HTTPException(status_code=401, detail="无效的token")
        except jwt.ExpiredSignatureError:
            raise HTTPException(status_code=401, detail="token已过期")
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"{repr(e)}")


class PermissionControl:

    @classmethod
    async def has_permission(
        cls,
        request: Request,
        current_user: User = Depends(AuthControl.is_authed)
    ) -> None:
        return


DependAuth = Depends(AuthControl.is_authed)
DependPermission = Depends(PermissionControl.has_permission)
